'''
Created on 2013-12-04

@author: yma
'''
#coding:GBK
import threading,os, ConfigParser,unittest
from log import Logger
import sys
import time
import Configure
class TestBuilder(object):
    '''Class for store test session properties '''
    __instance = None 
    __mutex = threading.Lock()
    __buildOption = None
    __test_name = None
    def __init__(self,properties=None):
        self.__buildOption = properties
        self.__logger = Logger.getLogger()

    def setRunningTestName(self, testname=None):
        self.__test_name = testname

    def getRunningTestName(self):
        return self.__test_name


    @staticmethod
    def getBuilder(option=None):
        '''Return a single instance of TestBuilder object '''
        if(TestBuilder.__instance == None): 
            TestBuilder.__mutex.acquire()
            if(TestBuilder.__instance == None):
                TestBuilder.__instance = TestBuilder(option) 
            else: 
                pass  
            TestBuilder.__mutex.release() 
        else:
            pass     
        return TestBuilder.__instance

    def getScript(self,config_file='testcases_config.ini', case_name=None):
        git_path = os.getenv('path_git')
        config = ConfigParser.ConfigParser()
        config.readfp(open(config_file))
        return '%s%s'%(git_path,config.get("cases",case_name))

    def getConfig(self,config_file='testcases_config.ini', property=None):
        config = ConfigParser.ConfigParser()
        config.readfp(open(config_file))
        return config.get("config",property)

    def loadTestSuites(self,config_file='testcases_config.ini'):
        '''return test suite object'''

        return self.__loadTestingTestSuites(config_file)

    def __loadTestingTestSuites(self,config_file):
        '''Get and random list of test cases object'''
        # config = ConfigParser.ConfigParser()
        # config.readfp(open(config_file))
        # cases = config.options("cases")
        # names = []
        # for casename in cases:
        #     names.append('%s.%s.%s'%('run_test', 'test', casename))
        # return unittest.TestLoader().loadTestsFromNames(names)

        config = ConfigParser.ConfigParser()
        config.readfp(open(config_file))
        #Configure.REPORT_DIR =os.path.abspath(os.path.dirname(__file__) + os.sep + "report" + os.sep +time.strftime("executeResult_%Y-%m-%d-%H-%M-%S",time.localtime()))
        #os.makedirs( Configure.REPORT_DIR)
        # self.__logger = Logger(os.path.basename(__file__)).getlog()
        # self.__logger.debug("Start create report directory %s."%Configure.REPORT_DIR)

        # self.__logger.info("Test log is saved to %s"%Configure.REPORT_DIR)

        testsuit = config.options("cases")

        loader = unittest.TestLoader()
        suites_list = []
        #reportName = os.path.join(Configure.REPORT_DIR,"./result.html")
        if len(testsuit) <= 0:
            self.__logger.warn("Test suit is empty in runConfig.ini")
        else:
            for optionName in testsuit:
                testcase = config.get("cases",optionName)
                basPath = os.path.dirname(__file__)+os.sep+"Script"+os.sep+testcase
                filePath = os.path.dirname(__file__)+os.sep+"test"+os.sep+optionName+".py"
                if os.path.exists(filePath) : #&&os.path.exists(basPath)
                    module = os.path.basename(filePath).split(".")[0]
                    sys.path.append(os.path.dirname(filePath))
                    if isinstance(module, basestring):
                        moduleName = __import__(module)
                        for part in module.split('.')[1:]:
                            moduleName = getattr(moduleName, part)
                    else:
                        moduleName = module
                    suite = loader.loadTestsFromModule(moduleName)
                    suites_list.append(suite)
                else:
                    self.__logger.warning("Test script %s is not exist. Please check script directory or modify runConfig.ini" %filePath)
        # self.__logger.info("Start running test suite...")
        all_suite = unittest.TestSuite(suites_list)
        return all_suite
        #fp = file(reportName, 'wb')
        #runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
        #                                       title='HP Mobile Testing Report',
        #                                       description='Script Running:')
        #results = runner.run(all_suite)
        # self.__logger.info("Test suite execute done.")

        
                
        
        
        
